package com.xinliu.fastchat.interceptor;

/*
 @author: xinliu
 @email: 3536370493@qq.com
 @time : 2025/9/23 2:00
*/

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xinliu.fastchat.context.BaseContext;
import com.xinliu.fastchat.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        if (token == null || token.equals("")) {
            log.info("{} 以游客身份访问了:{}", request.getRemoteAddr(), request.getServletPath());
            //游客身份
            echo("以游客身份访问是没有权限的喵", response);
            return false;
        }

        try {

            //解析jwt
            DecodedJWT decodedJWT = JWTUtils.parse(token);

            Map<String, Claim> claims = decodedJWT.getClaims();

            Integer id = claims.get("id").asInt();

            log.info("请求了接口 用户id: {}", id);

            //记录当前用户id
            BaseContext.setId(id);

            return HandlerInterceptor.super.preHandle(request, response, handler);

        } catch (Exception e) {
            echo("登录状态异常喵", response);
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    public void echo(String msg, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;Charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println(msg);
    }
}
